package com.fdd.furns.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.fdd.furns.pojo.Member;
import com.fdd.furns.utils.WebUtils;
import com.google.gson.Gson;

/**
 * 权限验证的过滤器
 *
 * @author fdd
 * @create 2024-01-15 16:42
 */
public class AuthFilter implements Filter {
    private List<String> excludedUrls;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取到需要排除的url
        String excludedUrlsStr = filterConfig.getInitParameter("excludedUrls");
        String[] excludedSplitUrls = excludedUrlsStr.split(",");
        excludedUrls = Arrays.asList(excludedSplitUrls);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //得到请求的url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取url
        String url = request.getServletPath();

        //判断url是否在排除的url中
        //如果不在的话，继续判断是否登录，如果在的话，直接放行
        if (!excludedUrls.contains(url)) {
            //判断用户是否登录
            Member member = (Member) request.getSession().getAttribute("member");
            if (member == null) {//没有登录
                //判断是否是ajax请求
                if(!WebUtils.isAjax(request)){//不是ajax请求
                    request.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                }else{//是ajax请求
                    HashMap<String, String> resultMap = new HashMap<>();
                    resultMap.put("url", "views/member/login.jsp");
                    String jsonUrl = new Gson().toJson(resultMap);
                    servletResponse.getWriter().write(jsonUrl);
                }
                return;
            }



        }
        
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
